package com.kucai.yifaqapp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kucai.yifaqapp.R;
import com.kucai.yifaqapp.dagger.component.activity.DaggerLoginActivityComponent;
import com.kucai.yifaqapp.dagger.module.activity.LoginActivityModule;
import com.kucai.yifaqapp.model.network.entity.res.ResLogin;
import com.kucai.yifaqapp.presenter.activity.LoginActivityPresenter;
import com.kucai.yifaqapp.ui.view.LoginActivityView;
import com.kucai.yifaqapp.util.EventBus.refreshFragmentEvent;
import com.kucai.yifaqapp.util.Md5;
import com.kucai.yifaqapp.util.SpUtils;
import com.kucai.yifaqapp.widget.CheckView;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity<LoginActivityPresenter> implements LoginActivityView {

    TextView titleLeftTv;
    TextView headerTitle;
    EditText userNameEt;
    EditText userPassEt;
    Button loginBt;
    CheckBox yearpass;
    Button regsterBt;
    TextView playBt;
    CheckBox savepass;
    View Scrowlogin;
    EditText codeEt;
    @BindView(R.id.skinbg)
    LinearLayout skinbg;
    private String username;
    private String password;
    CheckView code_img;
    String[] code_reslut;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleLeftTv = findViewById(R.id.title_left_tv);
        headerTitle = findViewById(R.id.headerTitle);
        userNameEt = findViewById(R.id.user_name_et);
        userPassEt = findViewById(R.id.user_pass_et);
        loginBt = findViewById(R.id.login_bt);
        regsterBt = findViewById(R.id.regster_bt);
        playBt = findViewById(R.id.play_bt);
        savepass = findViewById(R.id.savepass);
        yearpass = findViewById(R.id.yearpass);
        Scrowlogin = findViewById(R.id.Scrowlogin);
        skinbg = findViewById(R.id.skinbg);
        codeEt = findViewById(R.id.code_et);
        code_img = findViewById(R.id.code_img);
        titleLeftTv.setText("返回");
        headerTitle.setText("登录");
        code_reslut = code_img.getValidataAndSetImage();//生成验证码
        code_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                code_reslut = code_img.getValidataAndSetImage();//生成验证码
            }
        });
        String str = SpUtils.getString(LoginActivity.this, "loginpass", "");
        if (str.equals("1")) {
            savepass.setChecked(true);
            userNameEt.setText("" + SpUtils.getString(LoginActivity.this, "username", ""));
            userPassEt.setText("" + SpUtils.getString(LoginActivity.this, "password", ""));
        } else {
            savepass.setChecked(false);
        }

        userNameEt.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Scrowlogin.setVisibility(View.VISIBLE);
                } else {
                    Scrowlogin.setVisibility(View.GONE);
                }
            }
        });
        userPassEt.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Scrowlogin.setVisibility(View.VISIBLE);
                } else {
                    Scrowlogin.setVisibility(View.GONE);
                }
            }
        });
        yearpass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int passwordLength = userPassEt.getText().length();
                userPassEt.setInputType(isChecked ?
                        (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) :
                        (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
                userPassEt.setSelection(passwordLength);
            }
        });


    }

    @Override
    protected void initDagger() {
        DaggerLoginActivityComponent.builder()
                .loginActivityModule(new LoginActivityModule(this))
                .build().inject(this);
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_login_activty;
    }

    @Override
    protected void ChangeSkin() {
        switch (SkinId) {
            case 17771:
                skinbg.setBackgroundResource(R.mipmap.skin_bg1);
                break;
            case 17772:
                skinbg.setBackgroundResource(R.mipmap.skin_bg2);
                break;
            case 17773:
                skinbg.setBackgroundResource(R.mipmap.skin_bg3);
                break;
            default:
                skinbg.setBackgroundResource(R.mipmap.skin_bg1);
        }
    }

    @OnClick({R.id.title_left_tv, R.id.login_bt, R.id.regster_bt, R.id.play_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_tv:
                finish();
                break;
            case R.id.login_bt:

                password = Md5.toMd5(userPassEt.getText().toString().trim());
                username = userNameEt.getText().toString().trim();

                if (!TextUtils.isEmpty(password) && !TextUtils.isEmpty(username)) {
                    if (savepass.isChecked()) {
//                    SYSOUtils.sOut_("保存密码");
                        SpUtils.putString(LoginActivity.this, "username", username);
                        SpUtils.putString(LoginActivity.this, "password", userPassEt.getText().toString().trim());
                        SpUtils.putString(LoginActivity.this, "loginpass", "1");//记录复选框状态
                    } else {
                        SpUtils.clearusername(this);
                        SpUtils.clearpassword(this);
                        SpUtils.clearloginpass(this);
                    }
                    //开始检验本地验证码
                    String yanzheng = code_reslut[0] + code_reslut[1] + code_reslut[2] + code_reslut[3];
                    if (codeEt.getText().toString().equals(yanzheng)) {
                        mPresenter.login(username, password);
                    } else {
                        Toast.makeText(LoginActivity.this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "您未输入用户名或密码", Toast.LENGTH_SHORT);
                }
                break;
            case R.id.regster_bt:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                finish();
                break;
            case R.id.play_bt:
                mPresenter.logindemo();
                break;
        }
    }


    @Override
    public void onfail(ResLogin resLogin) {
        //登录失败了
        Toast.makeText(this, resLogin.msg, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void logindemo() {
        finish();
    }

    @Override
    public void onsuccess() {
        EventBus.getDefault().postSticky(new refreshFragmentEvent("refresh"));
        finish();
    }

    /**
     * 解析
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * 将指定byte数组以16进制的形式打印到控制台
     *
     * @param b
     */
    public static void printHexString(byte[] b) {
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            System.out.print(hex.toUpperCase());
        }

    }

    /**
     * Convert char to byte
     *
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789abcdef".indexOf(c);
    }

}
